import 'package:dio/dio.dart';
import 'package:libflutter/logger/src/logger.dart';

/// Token拦截器
class TokenInterceptors extends InterceptorsWrapper {
  late String? _token;
  late String? _crmId;

  void setTokenAndCrmId({required String token, required String crmId}) {
    _token = token;
    _crmId = crmId;
  }

  @override
  onRequest(RequestOptions options, handler) async {
    try {
      if (_token != null) {
        options.headers["token"] = _token;
      }
      if (_crmId != null) {
        options.headers["crmId"] = _crmId;
      }
    } catch (e) {
      print("TokenInterceptors ${e}");
    }
    return super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    Logcat.D("${response.realUri}");
    if (response.realUri.toString().contains("app/sys/login")) {
      _token = response.data["data"]["token"];
      _crmId = response.data["data"]["userInfo"]["crmId"];
    }
    super.onResponse(response, handler);
  }
}
